/*
 * @Description:
 * @Author: lz
 * @Date: 2022-12-22 20:06:19
 * @LastEditTime: 2022-12-29 21:57:22
 * @LastEditors: lz
 */
import qs from 'qs'
import axios from "axios";
import { Message } from "element-ui";
import Crypto from '@/utils/crypto'
import { Loading } from "element-ui";
import router from '@/router'

// axios.defaults.headers["Content-type"] = "application/json;charset=utf-8";
const Service = axios.create({
  baseURL: "/zhmsbg",
  timeout: 150000
});

let loadingInstance = null;

//请求拦截器
Service.interceptors.request.use(config => {
  const token = localStorage.getItem('X-Access-Token') || ''

  loadingInstance = Loading.service();
  config.headers['clientId'] = Crypto.encrypt('NB6N66Eq3cshSi8DKxmc5W5Qkc4r7p3I')
  config.headers['clientSecret'] = Crypto.encrypt('AVe5dIGES3nhrXDl3ez65XoaQaw4KMCS')
  config.headers['sign'] = Crypto.encrypt('NB6N66Eq3cshSi8DKxmc5W5Qkc4r7p3IAVe5dIGES3nhrXDl3ez65XoaQaw4KMCS')
  config.headers['responseType'] = 'blob'
  if (token) {
    // config.headers['X-Access-Token'] = token
    config.headers['X-Access-Token'] = Crypto.encrypt(token)
  }
  if (config.formData) {
    const formData = new FormData();
    for (const key in config.data) {
      formData.append(key, config.data[key]);
    }
    config.data = formData;
  }
  return config;
});
//响应拦截器
Service.interceptors.response.use(
  res => {
    loadingInstance && loadingInstance.close();
    if (res.data.code === 0) {
      return res.data;
    } else {
      Message.error(res.data.msg);
      return Promise.reject(res.data.msg || "Error");
    }
  },
  async error => {
    loadingInstance && loadingInstance.close();
    if (error.message && error.message === 'Request failed with status code 401') {
      await router.replace({
        path: '/login'
      })
    }
    return Promise.reject(error);
  }
);

const get = (url, params = {}) =>
  Service({
    method: "get",
    url,
    params
  });
const post = (url, data = {}) =>
  Service({
    method: "post",
    url,
    data
  });
// 表单查询
const postFormData = (url, data) =>
  Service({
    method: "post",
    url,
    data: qs.stringify(data)
  });
const postUpload = (url, file) => {
  const data = new FormData();
  data.append("file", file);
  return Service({
    method: "post",
    url,
    headers: {
      "Content-Type": "multipart/form-data"
    },
    data
  });
};

const put = (url, params = {}, data = {}) =>
  Service({
    method: "put",
    url,
    params,
    data
  });

const del = (url, params = {}, data = {}) =>
  Service({
    method: "delete",
    url,
    params,
    data
  });
const uploadFile = (file) => postUpload('/common/interface/upload_img', file)

export { postFormData, postUpload, get, post, put, del, uploadFile };
export default Service;
